<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_matching_dist($in_year, $in_month, $in_matching_percent){
/*
This function takes all the matching bonus for the month and will automatically adjust the payout in such that all the bonus
payout (including matching bonus, exclude stockist fee) is at 55%.

On successful commission calculation, it will return boolean true, else it will return the error messages

changelog:
Date: 5-May-2010
Desc: drop payout percent, use matching percent instead
*/

	global $vars;
	$db=$vars["db"];
	$maintenance_percent = $vars['maintenance_percent'];
	$max_maintain = $vars['max_maintain'];
	
	$start_time=mktime(0, 0, 0, $in_month, 1, $in_year);
	$calc_date['start']=date('Y-m-d H:i:s', mktime(0, 0, 0, $in_month, 1, $in_year));
	$calc_date['end']=date('Y-m-d H:i:s', mktime(23, 59, 59, $in_month+1, 0, $in_year));
	$maintain_time=mktime(0, 0, 0, $in_month+1, 1, $in_year);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	
	$qi = 0;
	$quid = array();
	$t = @mysql_num_rows($r=mysql_query("select distinct(uid) as uid from $db->member_comm where type='m' and year='$in_year' and month='$in_month' and status='confirmed'"));
	for($i=0;$i<$t;$i++){
		$comm = mysql_fetch_assoc($r);
		$uid = $comm['uid'];
		$total_sale = @mysql_result(mysql_query("select sum(total_bv) from $db->purchase where uid='$uid' and no_bv!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"), 0) or 0;
		$total_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$in_year' and month='$in_month'"), 0) or 0;
		$ps = $total_sale + $total_maintain;
		if($ps >= $max_maintain){
			$quid[$qi++] = $uid;
		}
	}
	if(count($quid)){
		/*$matching_total = @mysql_result(mysql_query("select sum(amount) from $db->member_comm where type='m' and uid in (".implode(',', $quid).") and year='$in_year' and month='$in_month' and status='confirmed'"), 0) or 0;
		$other_total = @mysql_result(mysql_query("select sum(amount) from $db->member_comm where type in ('r','p') and year='$in_year' and month='$in_month' and status='confirmed'"), 0) or 0;
		$sales_total=@mysql_result(mysql_query("select sum(total_bv) from $db->purchase where status='confirmed' and no_bv!='y' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"), 0) or 0;
		$pool_total = 0;
		$pool_total+=round($sales_total*$vars['pool'][1]['percent']/100, 2);
		$pool_total+=round($sales_total*$vars['pool'][2]['percent']/100, 2);
		$pool_total+=round($sales_total*$vars['pool'][3]['percent']/100, 2);
		$comm_total = $matching_total + $other_total + $pool_total;
		
		$payout_percent = $comm_total / $sales_total * 100;
		$matching_percent = $matching_total / $sales_total * 100;
		$matching_adjusted = false;
		if($payout_percent > $projected_payout_percent){
			$diff_percent = $payout_percent - $projected_payout_percent;
			if($diff_percent > $matching_percent){
				$adjust_matching_percent = 0;
				$percent2 = 100;
			}else{
				$adjust_matching_percent = $matching_percent - $diff_percent;
				$adjust_matching_percent = round($adjust_matching_percent / $matching_percent * 100, 2);
				$percent2 = $adjust_matching_percent;
			}
			$matching_adjusted = true;
		}else{
			$percent2 = 100;
		}*/

		$adjust_matching_percent = $in_matching_percent;
		$percent2 = $adjust_matching_percent;
		$t = @mysql_num_rows($r=mysql_query("select * from $db->member_comm where type='m' and uid in (".implode(',', $quid).") and year='$in_year' and month='$in_month' and status='confirmed'"));
		for($i=0;$i<$t;$i++){
			$comm = mysql_fetch_assoc($r);
			if($adjust_matching_percent > 0){
				$amount2 = round($comm['amount'] * $adjust_matching_percent / 100, 2);
			}else{
				$amount2 = $comm['amount'];
			}
			$sql = "update $db->member_comm set amount2='$amount2', percent2='$percent2' where id='$comm[id]' limit 1";
			if(!mysql_query($sql)){
				$update_err .= "$sql\n";
			}else{
				$member_comm[$comm['uid']] += $amount2;
			}
		}
	}
	
	if ($member_comm){
		foreach ($member_comm as $uid => $amount){
			$total_maintain_amount = $maintain_amount = round($amount * $maintenance_percent / 100, 2);
			$next_month_maintain = @mysql_result(mysql_query("select sum(amount) from $db->member_maintain where uid='$uid' and year='$maintain_year' and month='$maintain_month'"), 0) or 0;
			if($next_month_maintain < $max_maintain){
				$maintain_amount = round($amount * $maintenance_percent / 100, 2);
				if($maintain_amount + $next_month_maintain > $max_maintain){
					$maintain_amount = $max_maintain - $next_month_maintain;
				}
				//insert into member_maintain with uid = uid, type = plana, comm_type = sponsor bonus, percent = maintain[plana], amount = maintain_plana, pv = maintain_value_to_pv, date
				$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, cdate)
				values ('$uid', 'm', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '".ndate()."')";
				if(!mysql_query($sql)){
					$insert_main_err.="UID: $uid, comm code: m, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month\n";
				}
			}else{
				$maintain_amount = 0;
			}
			
			$actual_amount = $amount - $total_maintain_amount;
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $actual_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from bulk matching commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}else{
				$new_eid = mysql_insert_id();
				$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
				if(!$last_bal){
					$last_bal = 0;
				}
				$last_bal += $amount;
				@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
			}
			
			if($maintain_amount > 0){
				//insert ewallet record for maintenance
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $maintain_amount;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				//update member swallet = swallet + maintain_amount
				if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
					$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
				}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_swrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_swallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $maintain_amount;
					@mysql_query("update $db->member_swallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			//mall point
			$mall_point = $total_maintain_amount - $maintain_amount;
			if($mall_point > 0){
				//insert ewallet record for maintenance
				if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$mall_point', '".addslashes("Debited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_ewrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_ewallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= $mall_point;
					@mysql_query("update $db->member_ewallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
				
				//update member mwallet = mwallet + mall_point
				if(!mysql_query($sql="update $db->users set mwallet=mwallet+$mall_point where id='$uid' limit 1")){
					$update_mw_err.="UID: $uid, amount: $mall_point\n";
				}elseif(!mysql_query($sql="insert into $db->member_mwallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$mall_point', '".addslashes("Credited $vars[currency]".number_format($mall_point, 2)." for maintenance from bulk matching commission received.")."', '".ndate()."')")){
					$insert_mwrec_err.=$sql."\n";
				}else{
					$new_eid = mysql_insert_id();
					$last_bal = @mysql_result(mysql_query("select bal from $db->member_mwallet_record where uid='$uid' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal += $mall_point;
					@mysql_query("update $db->member_mwallet_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
		}
	}
	
	if($update_err || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($update_err? "\nFailed Updating Matching Bonus:\n\n$update_err" : "").
	($insert_main_error? "Failed Maintenance Calculation:<br />\n<br />\n$insert_main_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "").
	($update_mw_err? "\nError crediting $vars[mwallet_title]:\n\n$update_mw_err" : "").
	($insert_mwrec_err? "\nError crediting $vars[mwallet_title] transactin record:\n\n$insert_mwrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>